<?php
require_once 'lucene/chinese.php';

class SearchController extends Zend_Controller_Action {

	const SEARCH_INVITATION = 0;
	const SEARCH_FRIEND = 1;
	
	private $invitation;

	public function init() {
		$this->invitation = new Invitation();
	}

	/**
	 * search page index.
	 */
	public function indexAction() {
		$filters = array('searchKey' => array('StringTrim', 'StripTags'));
		$validators = array('searchKey' => array('presence' => 'required'));
		$input = new Zend_Filter_Input($filters, $validators, $_POST);
		if ($input->isValid()) {
			$searchKey = $input->getEscaped('searchKey');
				
			//do search
			//$this->invitation->addToIndex(2);
		}
	}

	/**
	 * Search result action.
	 */
	public function searchresultAction() {
		if ($this->_helper->user->isLoggedIn()) {
			$searchKeys = explode(' ', trim($this->_getParam('searchKey')));
			if (!is_array($searchKeys) || empty($searchKeys[0])) {
				throw new Exception('Search Key is null');
			}
			$searchResult = array();
			$searchScope = self::SEARCH_INVITATION;
	//		echo 'Find '.count($queryHits)." of ".$index->count()." records: \n";
			
			$searchResult[self::SEARCH_INVITATION] = $this->generateResult(self::SEARCH_INVITATION, $searchKeys);
			$searchResult[self::SEARCH_FRIEND] = $this->generateResult(self::SEARCH_FRIEND, $searchKeys);
			$this->view->searchKeys = $searchKeys;
			$this->view->searchResult = $searchResult;
		} else {
			$this->_redirect('user/login');
		}
	}

	/**
	 * Generate result according to search scope.
	 * 
	 * @param $searchScope
	 * @param $searchKeys
	 * @return return array which contains result
	 */
	private function generateResult($searchScope, $searchKeys) {
		$result = array();
		
		// Search different scope, search friend or invitation
		if ($searchScope == self::SEARCH_FRIEND) {
			$class = 'Custom_Friend';
			SearchIndexer::setIndexDirctory('custom_friend');
		} else if ($searchScope == self::SEARCH_INVITATION) {
			$class = 'Invitation';
			SearchIndexer::setIndexDirctory('invitation');	
		}
		
		
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
		try {
			$index = Zend_Search_Lucene::open(SearchIndexer::getIndexDirectory());
		} catch (Zend_Search_Lucene_Exception $e) {
			$this->_redirect('error/');
		}
		
		if (count($searchKeys) > 1) {
			$multiq = new Zend_Search_Lucene_Search_Query_MultiTerm();
			foreach ($searchKeys as $searchKey) {
			  $term1 = new Zend_Search_Lucene_Index_Term($searchKey);
			  $multiq->addTerm($term1);
			}
			$queryHits = $index->find($multiq);
		} else {
			$pattern = new Zend_Search_Lucene_Index_Term($searchKeys[0].'*');
			$userQuery = new Zend_Search_Lucene_Search_Query_Wildcard($pattern);
			$queryHits = $index->find($userQuery);
		}
		
		switch ($searchScope) {
			case self::SEARCH_INVITATION:
				$index = 0;
				foreach ($queryHits as $hit) {
					$array['content'] = $hit->content;
					$array['description'] = $hit->description;
					$array['date'] = $hit->date;
					$array['created'] = $hit->created;
					$result[$index++] = $array;
				}
				break;
			case self::SEARCH_FRIEND:
				$index = 0;
				foreach ($queryHits as $hit) {
					$array['username'] = $hit->username;
					$array['email'] = $hit->email;
					$result[$index++] = $array;
				}
				break;
		}
		return $result;
	}
	
	/**
	 * Reindex.
	 */
	public function reindexAction() {
		
		// index for inviatation
		$invitations = $this->invitation->findAll();
		SearchIndexer::setIndexDirctory('invitation');
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
		$index = Zend_Search_Lucene::create(SearchIndexer::getIndexDirectory());

		foreach($invitations as $invitation) {
			$class = 'Invitation';
			$doc = SearchIndexer::getDocument('Invitation', $invitation);
			SearchIndexer::_addToIndex($index, $doc);				
		}

		// index for friends
		$friends = UserRelation::findAllFriends();
		SearchIndexer::setIndexDirctory('custom_friend');
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
		$index = Zend_Search_Lucene::create(SearchIndexer::getIndexDirectory());
		foreach($friends as $friend) {
			$class = 'Custom_Friend';
			$doc = SearchIndexer::getDocument('Custom_Friend', $friend);
			SearchIndexer::_addToIndex($index, $doc);	
		}
		
		$index->commit();
		$index->optimize();
		echo count($friends);
		exit;
	}
	
	public function testsearchAction() {
		
		require_once 'lucene/chinese.php';
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
		
		$index = new Zend_Search_Lucene('/home/james/test_index');
		$keywords='中文';
		echo "Index contains {$index->count()} documents.\n";
		
		$query = Zend_Search_Lucene_Search_QueryParser::parse( $keywords, 'utf-8' );
		$hits = $index->find($query);
		
		foreach ($hits as $hit) {
			echo 'PID: '.$hit->PID.'<br>';
			echo 'Score: '.$hit->score.'<br>';
			echo 'url: '.$hit->url.'<br>';
			echo 'productName: '.$hit->productName.'<br>';
			echo 'lan: '.$hit->lan.'<br>';
		} 
		
		exit;
	}
	
	public function testcreateindexAction() {
		
		$productsData= array(
			0=>array("PID"=>1,"url"=>"http://www.cybozu.jp","productName"=>"garoon","Description"=>"garoon Description","lag"=>"en"),
			1=>array("PID"=>2,"url"=>"http://www.cybozu.jp","productName"=>"äshare360","Description"=>"中文share360 Description" ,"lag"=>"en"),
			2=>array("PID"=>3,"url"=>"http://www.cybozu.jp a","productName"=>"日本語の製品名前","Description"=>"日本語の製品","lag"=>"jp"),
			3=>array("PID"=>4,"url"=>"http://www.cybozu.jp a","productName"=>"中文产品名","Description"=>"中文产品描述","lag"=>"zh")
		);
		
		require_once 'lucene/chinese.php';
		Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
		$index=new Zend_Search_Lucene('/home/james/test_index',true);
		$doc = new Zend_Search_Lucene_Document();
		foreach ($productsData as $productData) {
			$doc->addField(Zend_Search_Lucene_Field::keyword('PID', $productData['PID'], 'UTF-8'));
			$doc->addField(Zend_Search_Lucene_Field::Text('url', $productData['url'], 'UTF-8'));
			$doc->addField(Zend_Search_Lucene_Field::Text('productName', $productData['productName'], 'UTF-8'));
			$doc->addField(Zend_Search_Lucene_Field::Text('Description', $productData['Description'], 'UTF-8'));
			$doc->addField(Zend_Search_Lucene_Field::unIndexed('lan', $productData['lan'], 'UTF-8'));  
			
			$index->addDocument($doc);
			$index->commit();
			$index->optimize(); 

		}
		
		exit;
	}
}
?>